package edu.hnu.cloudflightserver.listener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import edu.hnu.cloudflightserver.util.CommonUtil;
import edu.hnu.cloudflightserver.util.DataBaseUtil;
import edu.hnu.cloudflightserver.util.FileUtil;
import edu.hnu.cloudflightserver.util.LogUtil;

public class ServletContentInitListener implements ServletContextListener {

	@SuppressWarnings({ "rawtypes", "unused" })
	private static final Class cls = ServletContentInitListener.class;

	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void contextInitialized(ServletContextEvent arg0) {

		LogUtil.info("start init database!");
		initDatabase();
		DataBaseUtil.initConnectionPool();
		LogUtil.info("database init successfully!");

	}
	
	private static void initDatabase(){
		Properties pro = FileUtil.getPropertiesAtClassPath(CommonUtil.SQL_CONFIG_FILE_NAME);
		if (pro == null) {
			return;
		}
		try {
			Class.forName(pro.getProperty("c3p0.driverClass"));
		} catch (ClassNotFoundException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
			return;
		}
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			conn = DriverManager.getConnection(pro.getProperty("base.url"), pro.getProperty("c3p0.user"), pro.getProperty("c3p0.password"));
			ps = conn.prepareStatement("create database if not exists " + pro.getProperty("base.databasename") + ";");
			int flag = ps.executeUpdate();
			if (flag != 0) {
				conn = DriverManager.getConnection(pro.getProperty("c3p0.jdbcUrl"), pro.getProperty("c3p0.user"), pro.getProperty("c3p0.password"));
				ps=conn.prepareStatement("show tables");
				rs=ps.executeQuery();
				if(rs.next()){
					return;
				}
				InputStream is = FileUtil.getInputStreamAtClassPath(CommonUtil.SQL_FILE_NAME);
				BufferedReader br;
				try {
					br = new BufferedReader(new InputStreamReader(is, CommonUtil.FILE_ENCODING));
					String line;
					StringBuffer sb = new StringBuffer();
					while ((line = br.readLine()) != null) {
						sb.append(line);
						if (line.endsWith(";")) {
							LogUtil.info("create table : "+sb.toString());
							ps = conn.prepareStatement(sb.toString());
							ps.executeUpdate();
							sb = new StringBuffer();
						}
					}
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		} catch (SQLException e2) {
			e2.printStackTrace();
		} finally {
			DataBaseUtil.releaseConnection(conn, ps, rs);
		}
	}

}
